/*
 * @Description: 处理文件上传
 * @Autor: tao wenbo 2419421809@qq.com
 * @Date: 2023-05-19 10:02:58
 * @LastEditors: tao wenbo 2419421809@qq.com
 * @LastEditTime: 2023-05-19 16:20:40
 */
import express from "express";
import {asyncHandler} from "../middleware/asyncHandler"
import multer from "multer"
import path from "path";
import { PORT,ImgExt, CODE } from "../../utils/const"
import { getIpAddress } from "../../utils/getIp"
const router = express.Router()


// 设置存储路径
const storage = multer.diskStorage({
    destination: function( req, file, cb ){
        cb( null, path.resolve( __dirname, "../../../static", "upload" ) )
    },
    filename: function( res,file, cb ){ //设置文件名
        let filename = Date.now() + Math.random().toString(36).slice(-6) + path.extname(file.originalname)
        cb( null, filename)
    }
})

const upload = multer({
    storage,
    limits: {
        fileSize: 1024 * 1024 //允许1m的图片
    },
    fileFilter( req, file, cb ){ //文件筛选
        const extname = path.extname( file.originalname )
        console.log(extname);
        if( ImgExt.includes( extname ) ){
            cb(null, true)
        }else{
            cb( new Error( `您上传的文件格式为：${extname}，请上传图片文件` ) )
        }
    }
})

router.post( "/uploadImg", upload.single("img") ,asyncHandler( async ( req, res ) => {
    return {
        path: `http://${getIpAddress()}:${PORT}/static/upload/${req.file?.filename}`
    }
} ) )


export default  router